package com.guguskins.back.common.filter;


import com.guguskins.back.common.security.entity.GuUserSrcurity;
import com.guguskins.back.common.security.utils.ResponseUtil;
import com.guguskins.back.entity.vo.ResultVo;
import com.guguskins.back.utils.JwtUtil;
import com.guguskins.back.utils.RedisUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * @author duttonliu
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private final RedisUtil redisUtil;
    private final AuthenticationManager authenticationManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager, RedisUtil redisUtil) {
        this.authenticationManager = authenticationManager;
        this.redisUtil = redisUtil;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/adminUser/back/login", "POST"));
    }

    //1 获取表单提交用户名和密码
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        String username = request.getParameter("userName");
        String password = request.getParameter("userPass");

//            HuiAdminUserEntity user = new ObjectMapper().readValue(request.getInputStream(), HuiAdminUserEntity.class);
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>()));
    }

    //2 认证成功调用的方法
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        //认证成功，得到认证成功之后用户信息
        GuUserSrcurity user = (GuUserSrcurity) authResult.getPrincipal();

        //根据用户名生成token
        Map<String, Object> map = new HashMap<>(3);
        map.put("userName", user.getAdminUser().getUsername());
        map.put("permissionList", user.getJurisdictionList());
        String token = JwtUtil.createToken(user.getAdminUser().getId().toString(), map, null);
        //把用户名称和用户权限列表放到redis
//        redisUtil.setString("token_" + user.getAdminUser().getUsername(), token, 24L, TimeUnit.HOURS);
        //返回tokeng
//        ResponseUtil.out(response, ResultEntity.ok().data("token", token));
        map.put("token", token);
        ResponseUtil.out(response, ResultVo.success(map, "登录成功！"));
    }

    //3 认证失败调用的方法
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        ResponseUtil.out(response, ResultVo.fail(failed.getMessage()));
    }
}
